package com.ericd.filetransfer;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;

public class FileReceiveServlet extends HttpServlet {

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		DiskFileItemFactory factory = new DiskFileItemFactory();
		FileUpload fu = new FileUpload(factory);
		File tempDir = new File("d:\\temp");
		if(!tempDir.exists() || tempDir.isFile()) {
			tempDir.mkdirs();
		}
		factory.setRepository(tempDir);
		factory.setSizeThreshold(1000000);// 1M
		List<FileItem> list = null;

		try {
			list = fu.parseRequest(request);
			if (null != list) {
				Iterator<FileItem> iter = list.iterator();
				while (iter.hasNext()) {
					FileItem item = iter.next();
					String itemName = item.getName();
					if(itemName==null || itemName.equals("")) {
						continue;
					}
					if (!item.isFormField()) {
						item.write(new File("d:/"
								+ new File(item.getName()).getName()));
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}
